package com.qiantu.phone.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.entity.ApplyTransferBean;
import com.qiantu.api.entity.SmsBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.exception.ResultException;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.other.LimitCharLengthTextWatcher;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.StringUtil;
import com.qiantu.phone.widget.CursorFrameTextView;
import com.qiantu.phone.widget.EditTextLayout;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class HouseTransferActivity extends AppActivity {

    private TextView mText1;
    private TextView mText2;
    private TextView mMinePhone;
    private LinearLayout mStep1Ly;
    private EditText mEditSmsCode;
    private CursorFrameTextView mTvSmsCode1;
    private CursorFrameTextView mTvSmsCode2;
    private CursorFrameTextView mTvSmsCode3;
    private CursorFrameTextView mTvSmsCode4;
    private TextView mTvCountDown;
    private View mStep2Ly;
    private EditTextLayout mOtherPhone;
    private CheckBox mCheckbox;
    private View mStep3Ly;
    private TextView mBtnGetCode;
    private TextView tvAccount;
    private TextView tvNickname;
    private int mStep = 1;
    private String phone;
    private String smsType = "transfer_boyun";
    private String smsID;
    private EditText etCongratulations;
    private ApplyTransferBean mApplyTransferBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_house_transfer;
    }

    @Override
    protected void initView() {
        mText1 = findViewById(R.id.text1);
        mText2 = findViewById(R.id.text2);
        mMinePhone = findViewById(R.id.mine_phone);
        mStep1Ly = findViewById(R.id.step_1_ly);
        mEditSmsCode = findViewById(R.id.edit_sms_code);
        mTvSmsCode1 = findViewById(R.id.tv_sms_code_1);
        mTvSmsCode2 = findViewById(R.id.tv_sms_code_2);
        mTvSmsCode3 = findViewById(R.id.tv_sms_code_3);
        mTvSmsCode4 = findViewById(R.id.tv_sms_code_4);
        mTvCountDown = findViewById(R.id.tv_count_down);
        mStep2Ly = findViewById(R.id.step_2_ly);
        mOtherPhone = findViewById(R.id.other_phone);
        etCongratulations = findViewById(R.id.congratulations);
        mCheckbox = findViewById(R.id.checkbox);
        mStep3Ly = findViewById(R.id.step_3_ly);
        tvAccount = findViewById(R.id.tv_account);
        tvNickname = findViewById(R.id.tv_nickname);
        mBtnGetCode = findViewById(R.id.btn_get_code);
        mMinePhone.setEnabled(false);
        etCongratulations.addTextChangedListener(new LimitCharLengthTextWatcher(etCongratulations, 200));
        setOnClickListener(R.id.tv_sms_code_1, R.id.tv_sms_code_2, R.id.tv_sms_code_3
                , R.id.tv_sms_code_4, R.id.btn_get_code, R.id.tv_count_down, R.id.send_msg_tv);
    }

    private void go2step(int i) {
        mStep = i;
        mStep1Ly.setVisibility(View.GONE);
        mStep2Ly.setVisibility(View.GONE);
        mStep3Ly.setVisibility(View.GONE);
        if (1 == i){
            mStep1Ly.setVisibility(View.VISIBLE);
            mBtnGetCode.setText(R.string.verify_and_transfer);
            mMinePhone.setText(phone);
            initStep1View();
        }else if (2 == i){
            mStep2Ly.setVisibility(View.VISIBLE);
            mBtnGetCode.setText(R.string.common_step_next);
            mBtnGetCode.setEnabled(false);
            initCodeView();
            showTvSmsCodeSoftInput();
            //开始倒计时
            startCountDown();
        }else if (3 == i){
            mStep3Ly.setVisibility(View.VISIBLE);
            mBtnGetCode.setText(R.string.cancel_transfer);
            mBtnGetCode.setEnabled(true);
            tvAccount.setText(getString(R.string.transfer_account_holder, mApplyTransferBean.getRecipientPhone()));
            tvNickname.setText(getString(R.string.transfer_nickname_holder, mApplyTransferBean.getRecipientName()));
        }
    }

    private void initStep1View() {
        mOtherPhone.getEditText().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(StringUtil.isPhoneLegal(String.valueOf(s))){
                    mBtnGetCode.setEnabled(true);
                }else{
                    mBtnGetCode.setEnabled(false);
                }
            }
        });
    }

    @Override
    protected void initData() {
        phone = AppApplication.getInstance().getLoginInfo().getUserInfo().getPhone();
        getLatestTransferDetail();
    }

    private CursorFrameTextView.OnPasteCallback mOnPasteCallback;
    private void initCodeView(){
        mEditSmsCode.setText(null);
        mTvSmsCode1.setSelected(true);
        if (mOnPasteCallback == null) {
            mOnPasteCallback = new CursorFrameTextView.OnPasteCallback() {
                @Override
                public void onPaste(String data) {
                    if (data == null){
                        return;
                    }
                    if (data.length()>4){
                        data = data.substring(0, 4);
                    }
                    mEditSmsCode.setText(data);
                    mEditSmsCode.setSelection(data.length());
                }
            };
        }
        mTvSmsCode1.setOnPasteCallback(mOnPasteCallback);
        mTvSmsCode2.setOnPasteCallback(mOnPasteCallback);
        mTvSmsCode3.setOnPasteCallback(mOnPasteCallback);
        mTvSmsCode4.setOnPasteCallback(mOnPasteCallback);
        mEditSmsCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                for (int i = 0; i < 4; i++) {
                    int currentLength = s.length();
                    String s1 = i < currentLength ? String.valueOf(s.charAt(i)) : "";
                    switch (i) {
                        case 0:
                            mTvSmsCode1.setText(s1);
                            if (currentLength >= i) {
                                mTvSmsCode1.setSelected(true);
                            } else {
                                mTvSmsCode1.setSelected(false);
                            }
                            break;
                        case 1:
                            mTvSmsCode2.setText(s1);
                            if (currentLength >= i) {
                                mTvSmsCode2.setSelected(true);
                            } else {
                                mTvSmsCode2.setSelected(false);
                            }
                            break;
                        case 2:
                            mTvSmsCode3.setText(s1);
                            if (currentLength >= i) {
                                mTvSmsCode3.setSelected(true);
                            } else {
                                mTvSmsCode3.setSelected(false);
                            }
                            break;
                        case 3:
                            mTvSmsCode4.setText(s1);
                            if (currentLength >= i) {
                                mTvSmsCode4.setSelected(true);
                            } else {
                                mTvSmsCode4.setSelected(false);
                            }
                            break;
                    }
                    if (s.length() == 4) {
                        hideKeyboard(mEditSmsCode);
                        mBtnGetCode.setEnabled(true);
                    }else{
                        mBtnGetCode.setEnabled(false);
                    }
                }
            }
        });
    }

    private int countDownTime;
    private Handler mHandler;
    private void startCountDown(){
        countDownTime = 60;
        if(mHandler == null){
            mHandler = new Handler();
        }
        mHandler.post(countDownRunnable);
    }

    private Runnable countDownRunnable = new Runnable() {
        @Override
        public void run() {
            countDownTime--;
            mTvCountDown.setText(countDownTime + getString(R.string.get_again_count_down));
            mTvCountDown.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
            mTvCountDown.setEnabled(false);
            if(countDownTime == 0){
                mTvCountDown.setText(R.string.get_again);
                mTvCountDown.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                mTvCountDown.setEnabled(true);
                return;
            }
            mHandler.postDelayed(countDownRunnable, 996);
        }
    };

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_sms_code_1:
            case R.id.tv_sms_code_2:
            case R.id.tv_sms_code_3:
            case R.id.tv_sms_code_4:
                showTvSmsCodeSoftInput();
                break;
            case R.id.tv_count_down:
                getCode();
                break;
            case R.id.btn_get_code: {
                switch (mStep) {
                    case 1:
                        getCode();
                        break;
                    case 2:
                        codeVerify();
                        break;
                    case 3:
                        cancelTransfer();
                        break;
                }
                break;
            }
            case R.id.send_msg_tv:

                break;
        }
    }

    private void codeVerify(){
        Map data = new HashMap<>();
        data.put("mobile", phone);
        data.put("code", mEditSmsCode.getText().toString());
        data.put("smsType", smsType);
        data.put("smsID", smsID);
        LLHttpManager.codeVerify(this, data, new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onSucceed(HttpData<Void> result) {
                houseTransfer();
            }
        });
    }

    private void houseTransfer() {
        String sPhone = mOtherPhone.getText().toString();
        if (!StringUtil.isPhoneLegal(sPhone)) {
            toast(R.string.phone_error_hint);
            return;
        }
        boolean isKeepMember = mCheckbox.isChecked();
        Map<String, Object> data = new HashMap<>();
        data.put("houseSerialNo", AppApplication.getInstance().getCurrentHouseSerialNo());
        data.put("phone", sPhone);
        data.put("isKeepMember", isKeepMember);
        data.put("smsId", smsID);
        data.put("smsType","transfer_boyun");
        data.put("congratulations", etCongratulations.getText().toString());
        LLHttpManager.applyTransfer(this, data, new HttpCallback<HttpData<ApplyTransferBean>>(this){
            @Override
            public void onSucceed(HttpData<ApplyTransferBean> result) {
                if(result != null && result.getData() != null){
                    mApplyTransferBean = result.getData();
                }
                go2step(3);
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(e.getMessage());
            }
        });
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;
    private void cancelTransfer() {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(this)
                    .setHint(getString(R.string.cancel_transfer_process))
                    .setLeftBtnText(getString(R.string.close))
                    .setRightBtnText(getString(R.string.cancel_transfer))
                    .setContent(R.string.cancel_transfer_hint)
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            LLHttpManager.cancelTransfer(HouseTransferActivity.this, mApplyTransferBean.getTransferSerialNo(), new HttpCallback<HttpData<Void>>(HouseTransferActivity.this){
                                @Override
                                public void onSucceed(HttpData<Void> result) {
                                    ToastUtils.show(R.string.cancel_success);
                                    finish();
                                }

                                @Override
                                public void onFail(Exception e) {
                                    if(e instanceof ResultException){
                                        ToastUtils.show(((ResultException)e).getHttpData().getMessage());
                                    }else{
                                        ToastUtils.show(R.string.cancel_failed);
                                    }
                                }
                            });
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialog.show();
    }

    private void getLatestTransferDetail(){
        LLHttpManager.getLatestTransferDetail(this, AppApplication.getInstance().getCurrentHouseSerialNo(), new HttpCallback<HttpData<ApplyTransferBean>>(null){
            @Override
            public void onStart(Call call) {
                showDialog();
            }

            @Override
            public void onSucceed(HttpData<ApplyTransferBean> result) {
                if(result != null){
                    mApplyTransferBean = result.getData();
                    if(mApplyTransferBean != null){
                        //1:待交付 2:已交付 3:已拒绝 4:已撤回
                        switch (mApplyTransferBean.getState()){
                            case 1:
                                go2step(3);
                                break;
                            case 2:
                            case 3:
                            case 4:
                                go2step(1);
                                break;
                        }
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                if(e instanceof ResultException){
                    ResultException resultException = (ResultException) e;
                    if(resultException.getHttpData().getCode() == 12018){
                        go2step(1);
                    }
                }
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void showTvSmsCodeSoftInput() {
        mEditSmsCode.requestFocus();
        showKeyboard(mEditSmsCode);
    }

    private void getCode(){
        Map<String, Object> data = new HashMap<>();
        data.put("mobile", phone);
        data.put("smsType", smsType);
        LLHttpManager.sendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
            @Override
            public void onSucceed(HttpData<SmsBean> data) {
                if(data.isRequestSucceed()){
                    toast(R.string.sms_code_send);
                    smsID = data.getData().getSmsID();
                    go2step(2);
                }
            }
        });
    }
}